package org.dftproject.patml;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dftproject.genesis.core.http.HttpManager;
import org.dftproject.genesis.data.genealogy.IPerson;
import org.dftproject.patml.data.PatmlPerson;
import org.dftproject.patml.data.PatmlSite;

public class DataExtractor {
	
	private static final DataExtractor singleton = new DataExtractor();
	
	private final static Pattern urlPattern = Pattern.compile("^(https?://.*?/)[^/]*\\?(.*?)(?:#.*)?$");
	private final static Pattern queryStringPattern = Pattern.compile("([^=&]+)=([^&]+)&");

	private DataExtractor() {
	}
	
	public static DataExtractor getDefault() {
		return singleton;
	}
	
	public IPerson getPerson(String url) {
		String content = HttpManager.getDefault().getWebPage(url);
		if (content != null) {
			PatmlSite site = getSite(url, content);
			if (site != null)
				return new PatmlPerson(site, site.getPersonId(url));
		}
		
		return null;
	}
	
	protected PatmlSite getSite(String url, String content) {
		if (url.contains("getperson.php") && content.contains("The Next Generation of Genealogy Sitebuilding")) {
			Matcher matcher = urlPattern.matcher(url);
			if (matcher.matches()) {				
				String siteUrl = matcher.group(1);
				String tree = null;
				
				String queryString = matcher.group(2);
				if (!queryString.endsWith("&"))
					queryString += "&";
				matcher = queryStringPattern.matcher(queryString);
				while (matcher.find()) {
					if ("tree".equalsIgnoreCase(matcher.group(1)))
						tree = matcher.group(2);
				}
				
				return new TngSite(siteUrl, tree);
			}
		} else if (url.contains("m=family") && content.contains("Retrospect-GDS")) {
			Matcher matcher = urlPattern.matcher(url);
			if (matcher.matches()) {				
				String siteUrl = matcher.group(1);				
				return new RgdsSite(siteUrl);
			}
		}
		return null;
	}
	
}
